package cn.cdeden.knowledge.controller.formDoc;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.dto.SysFormDocDto;
import cn.cdeden.knowledge.domain.dto.SysFormDocQueryParam;
import cn.cdeden.knowledge.domain.dto.TeamFilesTreeDto;
import cn.cdeden.knowledge.enums.ResultEnum;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.knowledge.utils.FileStorageUtils;
import cn.cdeden.system.api.RemoteUserService;
import com.alibaba.fastjson.JSONObject;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author Chen
 * @date 2023-09-11
 **/
@RestController
@RequiredArgsConstructor
//@Api(tags = "表单文档数据管理")
@RequestMapping("/api/sysFormDoc")
public class SysFormDocController {

    private final TeamRoleService teamRoleService;

    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final SysFormDocService sysFormDocService;

    private final SysFormDocFileService sysFormDocFileService;

    private final PersonalFilesTreeService personalFilesTreeService;

    private final FileService fileService;

    private final TeamFilesTreeService teamFilesTreeService;

//    private final RemoteUserService userService;

    private final FileStorageUtils fileStorageUtils;

//    private final RepositoryService repositoryService;
//
//    private final IdentityService identityService;
//
//    private final RuntimeService runtimeService;

    private final EnterpriseFilesTreeService enterpriseFilesTreeService;


    @GetMapping(value = "/query")
//    @Log("查询表单文档数据")
//    @ApiOperation("查询表单文档数据")
    public R<SysFormDocDto> query(SysFormDocQueryParam query) {
        return R.ok(sysFormDocService.query(query));
    }

    @PostMapping(value = "/create")
//    @Log("新增表单文档数据")
//    @ApiOperation("新增表单文档数据")
    public R create(@Validated @RequestBody SysFormDocDto resources) {
        //根据treeNodeId查出富文本文档id
            Long id = null;
            if (resources.getType().equals("0")||resources.getType().equals(TreeEnum.PERSONAL.getType())) {
                //我的文档
                PersonalFilesTree filesTrees = fileService.createText(resources.getTreeNodeId(), resources.getName());
                id = filesTrees.getId();
                resources.setType("0");
            } else {
                //团队文档
                if (!teamRelevanceRoleService.checkPermission(resources.getTreeNodeId(), resources.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.ADD.getParam())){
                    return R.fail(ResultEnum.PERM_ERROR.getNum(),"无新建权限，请联系管理员");
                }
                TeamFilesTreeDto teamFilesTreeDto = teamFilesTreeService.insert(resources.getTreeNodeId(), resources.getName(), resources.getTeamId(), TreeTypeEnum.RICHTEXT.getType());
                if (teamFilesTreeDto.getDuplicate()){
                    return R.fail("已有重名的文档");
                }
                //继承权限
                teamRelevanceRoleService.extendParentPerm(teamFilesTreeDto.getParentId(), String.valueOf(teamFilesTreeDto.getId()));
                resources.setType("1");
                id = teamFilesTreeDto.getId();
            }
            resources.setTreeNodeId(String.valueOf(id));
            return R.ok(sysFormDocService.insert(resources));
    }


    @PostMapping(value = "/update")
//    @Log("修改表单文档数据")
//    @ApiOperation("修改表单文档数据")
    public R update(@Validated @RequestBody SysFormDocDto resources) {
        String name = resources.getName();
        String treeNodeId = resources.getTreeNodeId();
        String type = resources.getType();
        SysFormDocQueryParam query = new SysFormDocQueryParam();
        query.setType(type);
        query.setTreeNodeId(treeNodeId);
        SysFormDocDto sysFormDocDto = sysFormDocService.query(query);
        resources.setId(sysFormDocDto.getId());
        if (name != null) {
            if (type.equals("0")) {
                //我的文档
                try {
                    fileService.updateName(treeNodeId, name);
                } catch (BadRequestException e) {
                    throw new RuntimeException(e);
                }
            } else {
                //团队文档
                boolean rename = false;
                if (!teamRelevanceRoleService.checkPermission(resources.getTreeNodeId(), resources.getTeamId(), LoginHelper.getLoginUser(),TeamParamEnum.UPDATE.getParam())){
                    return R.fail(ResultEnum.PERM_ERROR.getNum(),"无修改权限，请联系管理员");
                }
                TeamFilesTreeDto teamFilesTreeDto = new TeamFilesTreeDto();
                teamFilesTreeDto.setId(Long.valueOf(treeNodeId));
                teamFilesTreeDto.setRealName(name);
                rename = teamFilesTreeService.rename(teamFilesTreeDto);
                if (!rename) {
                    return R.fail("该文件名已存在!");
                }
            }
        }
        return R.ok(sysFormDocService.updateById(resources));
    }

//    @Log("个人/团队表单文档上传到企业库")
//    @ApiOperation("个人/团队表单文档上传到企业库")
//    @PostMapping(value = "/uploadFormDoc")
//    @ResponseBody
//    public R uploadFormDoc(@Validated @RequestBody UploadFormDocDto uploadFormDocDto) {
//
//        //组织数据，传入流程变量
//        Map<String, Object> variables = new HashMap<>();
//
//        String treeNodeId = uploadFormDocDto.getTreeNodeId();
//        String type = uploadFormDocDto.getType();
//        variables.put("user", FileUserUtils.getUser());
//        if (StringUtils.isEmpty(treeNodeId) || StringUtils.isBlank(treeNodeId))
//            throw new RuntimeException("团队文件夹id为空");
//        if (StringUtils.isEmpty(uploadFormDocDto.getParentId()) || StringUtils.isBlank(uploadFormDocDto.getParentId()))
//            throw new RuntimeException("企业文件夹id为空");
//        variables.put("parentId", uploadFormDocDto.getParentId());
//
//
//        String realName = null;
//        if (type.equals("0")){
//            PersonalFilesTree personalFilesTree = personalFilesTreeService.getById(uploadFormDocDto.getTreeNodeId());
//            realName =  personalFilesTree.getRealName();
//        }else {
//            TeamFilesTree teamFilesTree = teamFilesTreeService.getById(uploadFormDocDto.getTreeNodeId());
//            realName =  teamFilesTree.getRealName();
//        }
//        //企业判断重名文件
//        if (enterpriseFilesTreeService.nameRechecking(realName, String.valueOf(uploadFormDocDto.getParentId()), null) != null)
//            throw new RuntimeException("该企业文件夹下已有同名文档");
//
//        //表单文档的文件拷贝到临时库
//        User loginUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, SecurityUtils.getCurrentUsername()));
//        SysFormDocQueryParam sysFormDocQueryParam = new SysFormDocQueryParam();
//        sysFormDocQueryParam.setTreeNodeId(treeNodeId);
//        sysFormDocQueryParam.setType(type);
//        SysFormDocDto sysFormDocDto = sysFormDocService.query(sysFormDocQueryParam);
//        variables.put("sysFormDocDtoJson", JSONObject.toJSONString(sysFormDocDto));
//        SysFormDocFileQueryParam sysFormDocFileQueryParam = new SysFormDocFileQueryParam();
//        sysFormDocFileQueryParam.setFormDocId(String.valueOf(sysFormDocDto.getId()));
//        List<SysFormDocFileDto> sysFormDocFileDtos = sysFormDocFileService.queryAll(sysFormDocFileQueryParam);
//        List<Storage> storages = new ArrayList<>();
//        for (SysFormDocFileDto sysFormDocFileDto : sysFormDocFileDtos) {
//            Storage storage = fileStorageUtils.copy(loginUser.getId().toString(), loginUser.getUsername(), FileEnums.TEMPORARY_FILE, StorageFolderTypeEnum.TEMPORARY_FILES.getCode(), sysFormDocFileDto.getStorageId(), null, null);
//            storages.add(storage);
//        }
//        variables.put("storages", storages);
//
//
//        //必选流程，开启流程
//        try {
//            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
//                    .processDefinitionName("提交到企业表单文档")
//                    .latestVersion()
//                    .singleResult();
//            if (!Objects.nonNull(processDefinition)) {
//                throw new RuntimeException("请上传必存流程——提交到企业表单文档");
//            }
//            if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
//                throw new RuntimeException("流程已被挂起,请先激活流程");
//            }
//
//            // 设置流程发起人Id到流程中
//            User sysUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, SecurityUtils.getCurrentUser().getUsername()));
//            identityService.setAuthenticatedUserId(sysUser.getUsername());
//            variables.put("INITIATOR", sysUser.getUsername());
//            runtimeService.startProcessInstanceById(processDefinition.getId(), variables);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("流程启动错误");
//        }
//
//        return R.ok();
//    }

}
